﻿// See https://aka.ms/new-console-template for more information
using Modbus.Device;
using Modbus.Extensions.Enron;
using System.Diagnostics.Metrics;
using System.IO.Ports;
using System.Text;


Test();
Console.WriteLine("Hello, World!");

void Test()
{
    // 配置串口
    string portName = "COM2"; // 串口名称
    int baudRate = 9600; // 波特率
    Parity parity = Parity.None; // 无校验位
    int dataBits = 8; // 数据位
    StopBits stopBits = StopBits.One; // 停止位

    // 打开串口连接
    using (var serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits))
    {
        serialPort.Open();

        // 创建Modbus RTU从设备
        using (var modbusMaster = ModbusSerialMaster.CreateRtu(serialPort))
        {
            // 从设备地址
            byte slaveAddress = 1;

            // 起始寄存器地址
            ushort startAddress = 0;

            // 读取寄存器数量
            ushort numInputRegisters = 10;

            // 写入线圈
            // modbusMaster.WriteSingleCoil(slaveAddress, startAddress, true);

            // 读取线圈
            //var registers = modbusMaster.ReadCoils(slaveAddress, startAddress, numInputRegisters);

            // 5. 读取离散输入寄存器（功能码 02）
            // 返回值：bool[]，每个元素对应一个寄存器的状态（true=1，false=0）
            bool[] registers = modbusMaster.ReadInputs(
                slaveAddress: slaveAddress,
                startAddress: startAddress,
                numberOfPoints: numInputRegisters
            );



            // 写入寄存器
            //modbusMaster.WriteSingleRegister32(slaveAddress, startAddress, 663);
            //modbusMaster.WriteSingleRegister(slaveAddress, startAddress, 669);

            //modbusMaster.WriteSingleRegister(slaveAddress, 9, 669);

            // 读取寄存器
            // var registers = modbusMaster.ReadHoldingRegisters32(slaveAddress, startAddress, numInputRegisters);
            //var registers = modbusMaster.ReadHoldingRegisters(slaveAddress, startAddress, numInputRegisters);

            //{
            //    // 将ushort数组转换为byte数组
            //    byte[] bytes = new byte[registers.Length * 2];
            //    for (int i = 0; i < registers.Length; i++)
            //    {
            //        byte[] tempBytes = BitConverter.GetBytes(registers[i]);
            //        bytes[i * 2] = tempBytes[1];
            //        bytes[i * 2 + 1] = tempBytes[0];
            //    }

            //    // 将byte数组转换为字符串
            //    //string result = Encoding.ASCII.GetString(bytes);

            //    //Console.WriteLine($"读取的字符串是: {result}");
            //}

            // 输出读取的寄存器值
            for (int i = 0; i < registers.Length; i++)
            {
                Console.WriteLine($"Register {startAddress + i}: {registers[i]}");
            }
        }
    }
}
